package com.dminvoicemanager.printdoc;

import java.io.OutputStream;
import java.lang.reflect.Method;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import com.dminvoicemanager.DM_InvoiceMenu;
import com.dminvoicemanager.DM_List_Expand_Helper;
import com.dminvoicemanager.R;
import android.app.Activity;
import android.app.Dialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

public class DM_Print_Main_Invoice_Active extends Activity {
	private static final String TAG = null;
	private String DBNAME = "dminvoicemanager.db";
	private String TEMP_REP_INVOICESUMERY = "frepInvoiceSumery";
	private String INV_DETAILS = "FinvDet";
	private String INV_HEADER = "FinvHed";
	private String LOGPRINTSTRING = "FInvLogPrint";
	SQLiteDatabase mydb;
	String CurrentStringPrint, currentIndex;

	private String USER_SETTINGS = "usersettings";
	String item_result_1 = "0", item_result_2 = "0", item_result_3 = "0",
			item_result_4 = "0", item_result_5 = "0", item_result_6 = "0",
			item_result_7 = "0", TotalStrPrintDiscount, NetTotalValuePrint,SalesOrdNo ="",
			TotalInvoiceDiscount, TotalLineDiscount,StrDisPerRatio,printMainInvDiscount,Remarks,StrPrintDebAddressA,StrPrintDebAddressB,StrPrintDebAddressC,StrPrintDebPhone,totPiecesInCase,StrItemUnitPrice;
	TextView txtHeadingReports, dmreportfromdate, dmreporttodate,
			dmdisplayrepname, printtotinvdis,invoicediscountSummary,txtDistributoraddressb,printcusaddress,printcusaddressb,printcusphoneno;
	TextView printrefno, printdate, printcus, printtotcaseqty,
			printtotpiecesqty, printmktrettot, printgrosssalestot, printtotdis,
			printnettotal,printremark;
	TextView txtDistributorname, txtDistributoraddress, txtDistributorphone,
			txtSalesRepname, txtSalesRepPhone,txtprintsordrefno;
	String currentReportName, selectFromDate, selectToDate, currentUserTemp,
			currentUserPrefix, UserLocCode, StrPrintRefNo, StrPrintDate,
			StrPrintDebName, StrPrintCaseQty, StrPrintPiecesQty,
			StrPrintDiscount, MainRefNo,totalInvoiceDicountStr,totalGrossSalesValueStr,DealAddStra,DealAddStrb,DealAddStrc;
	Double PrintCaseQtyVal = 0.0, PrintPiecesQtyVal = 0.0,
			PrintSalesTotal = 0.0, PrintSalesRetTotal = 0.0,
			PrintDiscountVal = 0.0, TotalLineDiscountVal = 0.00,
			TotalInvoiceDiscountStr = 0.00;;
	String CurrentType = "0", PrintType, CurrentUser, TransType,title_Print_NO = "",printCaseQuantity,printPicesQuantity;
	int loopPrint = 0, logPrint = 0, countCountInv;
	int printIndex = 0;
	//DecimalFormat formatValues = new DecimalFormat("#,###.00");
	DecimalFormat formatValues = new DecimalFormat("#,###,##0.00");
	String currentRefNo;
	String DealNameStr, DealAddStr, DealMobStr;
	BluetoothAdapter mBTAdapter;
	BluetoothSocket mBTSocket = null;
	Dialog dialogProgress;
	String BILL, TRANS_ID;
	String PRINTER_MAC_ID;
	final String ERROR_MESSAGE = "There has been an error in printing the bill.";
	String Heading_a = "\r\n";
	String Heading_b = "";
	String Heading_c = "";
	String Heading_d = "";
	String Heading_bmh = "";
	String printSpaceName = "                    ";
	String printSpaceQty = "     ";
	String printLineSeperator = "________________________________________________";
	String mainName = "Maliban Biscuits Manufactories";
	String usernameStr,userphoneStr,usermobileStr,repPhone;
	
	public void BackToMainMenu(View view) {
		Intent myIntent = new Intent(view.getContext(), DM_InvoiceMenu.class);
		myIntent.putExtra("TAGID", "SALES");
		myIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
				| Intent.FLAG_ACTIVITY_NEW_TASK);
		startActivityForResult(myIntent, 0);
		finish();
		return;
	}

	public void PrintCurrentview(View view) {
		Log.v(TAG, "XXXXXXXX 2:" + currentRefNo);
		Intent myIntent = new Intent(view.getContext(),
				DM_Print_Main_Invoice_Active.class);
		myIntent.putExtra("TAGIDREFNO", MainRefNo);
		myIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
				| Intent.FLAG_ACTIVITY_NEW_TASK);
		startActivityForResult(myIntent, 0);
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.dm_transaction_doc_invoice);

		Bundle bundle = getIntent().getExtras();
		currentRefNo = bundle.getString("TAGIDREFNO");
		
		
		Log.d(TAG, "LENGTH 1: = " + printLineSeperator.length());
		Log.d(TAG, "LENGTH 2: = " + mainName.length());
		
		
		MainRefNo = currentRefNo.trim();
		txtDistributorname = (TextView) findViewById(R.id.salesdealernameval);
		txtDistributoraddress = (TextView) findViewById(R.id.salesdealeraddressval);
		txtDistributoraddressb = (TextView) findViewById(R.id.salesdealeraddressvalb);
		txtDistributorphone = (TextView) findViewById(R.id.salesdealerphoneval);
		txtSalesRepname = (TextView) findViewById(R.id.salesrepnameval);
		printtotinvdis = (TextView) findViewById(R.id.printtotinvdis);
		txtSalesRepPhone = (TextView) findViewById(R.id.salesrepphoneval);
		invoicediscountSummary = (TextView) findViewById(R.id.invoicediscountSummary);
		printrefno = (TextView) findViewById(R.id.printrefno);
		txtprintsordrefno = (TextView) findViewById(R.id.printsordrefno);
		printdate = (TextView) findViewById(R.id.printdate);
		printcus = (TextView) findViewById(R.id.printcus);
		printremark = (TextView) findViewById(R.id.invoiceremark);
		// Printing summay
		printtotcaseqty = (TextView) findViewById(R.id.printcaseqty);
		printtotpiecesqty = (TextView) findViewById(R.id.printpiecesqty);
		printmktrettot = (TextView) findViewById(R.id.printmktret);
		printgrosssalestot = (TextView) findViewById(R.id.printgrosssales);
		printtotdis = (TextView) findViewById(R.id.printtotdis);
		printnettotal = (TextView) findViewById(R.id.printnettotal);
		
		printcusaddress = (TextView) findViewById(R.id.printcusaddress);
		printcusaddressb = (TextView) findViewById(R.id.printcusaddressb);
		printcusphoneno = (TextView) findViewById(R.id.printcusphoneno);
		
		
		TextView txtHeading = (TextView) findViewById(R.id.txtHeading);
		txtHeading.setText("Invoice");
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);

		mydb.execSQL("DROP TABLE IF EXISTS FInvLogPrint");

		mydb.execSQL("create table if not exists "
				+ LOGPRINTSTRING
				+ "(print_id integer primary key autoincrement,printArray text not null);");
		selectCurrentPrinter();
		displayHeader();
		displaySalesRep();
		checkItems();

	}

	private void displaySalesRep() {
		// TODO Auto-generated method stub
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor surrentsalesrep = null;
		String userSettingsQuery;
		try {
			userSettingsQuery = "SELECT s.username,r.RepName,r.RepCode,r.repPhoneNo,r.RepMob From fSalRep r,usersettings s Where r.RepCode = s.username";
			// userSettingsQuery = "SELECT * From fSalRep";
			surrentsalesrep = mydb.rawQuery(userSettingsQuery, null);
			/*
			 * String query = "SELECT * FROM usersettings"; surrentsalesrep =
			 * mydb.rawQuery(query, null);
			 */
		} catch (Exception e) {
		}
		if (surrentsalesrep != null) {
			if (surrentsalesrep.getCount() > 0) {
				while (surrentsalesrep.moveToNext()) {

					usernameStr = surrentsalesrep.getString(1);
					String userphoneStrval = surrentsalesrep.getString(3);
					String usermobileStrvsl = surrentsalesrep.getString(4);

					userphoneStr = userphoneStrval.trim();
					usermobileStr = usermobileStrvsl.trim();

					if (usermobileStr.length() != 0
							&& userphoneStr.length() != 0) {
						repPhone = userphoneStr + "/" + usermobileStr;
						Log.v(TAG, "PPPPPPP 1: " + repPhone + "/");
					} else if (usermobileStr.length() != 0
							&& userphoneStr.length() == 0) {
						repPhone = usermobileStr;
						Log.v(TAG, "PPPPPPP 2: " + repPhone + "/");
					} else if (usermobileStr.length() == 0
							&& userphoneStr.length() != 0) {
						repPhone = userphoneStr;
						Log.v(TAG, "PPPPPPP 3: " + repPhone + "/");
					}
					else if(usermobileStr.length() == 0
							&& userphoneStr.length() == 0){
						repPhone = "+94";
					}
					txtSalesRepname
							.setText("Sales Rep : " + usernameStr.trim());
					txtSalesRepPhone.setText("Sales Phone : " + repPhone);
				}
			}
		}
		surrentsalesrep.close();
		mydb.close();
	}
	private void displayHeader() {
		// TODO Auto-generated method stub
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor curDisplayDistributor = null;
		try {
			String query = "SELECT * FROM fControl";
			curDisplayDistributor = mydb.rawQuery(query, null);
		} catch (Exception e) {
		}
		if (curDisplayDistributor != null) {
			if (curDisplayDistributor.getCount() > 0) {
				while (curDisplayDistributor.moveToNext()) {
					DealNameStr = curDisplayDistributor.getString(1);
					DealAddStra = curDisplayDistributor.getString(2);
					DealAddStrb = curDisplayDistributor.getString(3);
					DealAddStrc = curDisplayDistributor.getString(4);
					DealMobStr = curDisplayDistributor.getString(5);
					
					txtDistributorname.setText(DealNameStr);
					txtDistributoraddress.setText(DealAddStra);
					txtDistributoraddressb.setText(DealAddStrb + ", " +DealAddStrc + ".");
					txtDistributorphone.setText(DealMobStr);
				}
			}
		}
		curDisplayDistributor.close();
		mydb.close();
	}

	private void selectCurrentPrinter() {
		// TODO Auto-generated method stub
		SQLiteDatabase mydb;
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor curUserSettings = null;
		try {
			curUserSettings = mydb.query(USER_SETTINGS, null, null, null, null,
					null, null);
		} catch (Exception e) {
		}

		if (curUserSettings != null) {
			if (curUserSettings.getCount() > 0) {
				while (curUserSettings.moveToNext()) {
					CurrentUser = curUserSettings.getString(1);
					PRINTER_MAC_ID = curUserSettings.getString(8);
				}
			}
		}
		curUserSettings.close();
		mydb.close();
	}

	private void checkItems() {
		// TODO Auto-generated method stub
		ListView lvtypedes = (ListView) findViewById(R.id.dmstockloadingdetlist);
		// create the grid item mapping
		String[] fromtrdes = new String[] { "item_result_1", "item_result_2",
				"item_result_3", "item_result_4", "item_result_5",
				"item_result_6","item_result_6a", "item_result_7" };

		int[] totrdes = new int[] { R.id.printtrans, R.id.printindex,
				R.id.printitemname, R.id.printcasesQty, R.id.printpiecesQty,
				R.id.printdiscount,R.id.printitemssum, R.id.printrawvalue };

		// prepare the list of all records
		List<HashMap<String, String>> fillMapstrdes = new ArrayList<HashMap<String, String>>();

		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);

		Cursor allrowitemsdes = null;

		try {
			String query = "SELECT FD.RefNo,FD.Itemcode,FD.Type,FD.Amt,FD.CaseQty,FD.PiceQty,FD.itemDescription,FH.DebCode,FDE.DebName,FH.OutDis,FD.SeqNo,FH.TxnDate,FD.DisAmt,FH.TotalDis,FH.TotalAmt,FD.BDisAmt,FD.itemDisper,FD.itemdisperval,FH.outDisVal,FH.Remarks,FH.RefNo1,FDE.DebAdd1,FDE.DebAdd2,FDE.DebAdd3,FDE.DebTele,FD.refInvitemCaseQty,FD.itemUnitPrice FROM FinvDet FD,FinvHed FH,fDebtor FDE WHERE FH.RefNo = FD.RefNo AND FH.DebCode = FDE.DebCode AND FD.RefNo = '" + currentRefNo + "' ORDER BY FD.TxnType";

			allrowitemsdes = mydb.rawQuery(query, null);
			if (allrowitemsdes != null) {
				if (allrowitemsdes.getCount() > 0) {
					while (allrowitemsdes.moveToNext()) {
						countCountInv = countCountInv + 1;
						String indexcountinv = Integer.toString(countCountInv);
						logPrint = logPrint + 1;
						// PRINTER_MAC_ID = "AC:3F:A4:12:D7:E8";
						// PRINTER_MAC_ID = "00:22:58:3A:C6:49";
						// **********Printing**********
						if (logPrint == 1) {
							Heading_a = "          " + "Maliban Biscuits Manufactories" + "\r\n" + "             " + "#389,Galle road,Ratmalana" + "\r\n" + "                    " + "Sri Lanka" + "\r\n"+"               "+"Tel: 011 5 555000" +"\r\n" + "             " + "www.malibanbiscuits.com" +"\r\n" + "           "+ "maliban@malibanbiscuits.com" + "\r\n"+ printLineSeperator +"\r";
						}
						// **********Printing End**********
						StrPrintRefNo = allrowitemsdes.getString(0);
						StrPrintDate = allrowitemsdes.getString(11);
						StrPrintDebName = allrowitemsdes.getString(8);
						StrDisPerRatio = allrowitemsdes.getString(9);
						StrPrintCaseQty = allrowitemsdes.getString(4);
						TransType = allrowitemsdes.getString(2);
						StrPrintPiecesQty = allrowitemsdes.getString(5);
						StrPrintDiscount = allrowitemsdes.getString(12);
						TotalStrPrintDiscount = allrowitemsdes.getString(13);
						NetTotalValuePrint = allrowitemsdes.getString(14);
						TotalInvoiceDiscount = allrowitemsdes.getString(18);
						Remarks = allrowitemsdes.getString(19);
						SalesOrdNo = allrowitemsdes.getString(20);
						StrPrintDebAddressA = allrowitemsdes.getString(21);
						StrPrintDebAddressB = allrowitemsdes.getString(22);
						StrPrintDebAddressC = allrowitemsdes.getString(23);
						StrPrintDebPhone = allrowitemsdes.getString(24);
						totPiecesInCase = allrowitemsdes.getString(25);
						StrItemUnitPrice = allrowitemsdes.getString(26);

						// **********Printing**********
					                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    String printFormatSpaceHeadingmh = "------------------------";
						String printFormatSpaceHeadingmh1 = "                        ";
						String printGapAdjust = "                        ";
						/*	int lenght0 = DealNameStr.length();
						int length1 = subTitleamh.length();
						int lenght2 = length1 / 2;
						int length3 = length1 - 24; */  
						
						//Print Debtor Information
						int lengthDealA = DealNameStr.length();
						int lengthDealAB =  (48 - lengthDealA)/2;
						String printGapAdjustA = printGapAdjust.substring(0,Math.min(lengthDealAB, printGapAdjust.length()));
						
						int lengthDealB = DealAddStra.length();
						int lengthDealBB =  (48 - lengthDealB)/2;
						String printGapAdjustB = printGapAdjust.substring(0,Math.min(lengthDealBB, printGapAdjust.length()));
						
						String addressC = DealAddStrb + ", " +DealAddStrc + ".";
						int lengthDealC = addressC.length();
						int lengthDealCB =  (48 - lengthDealC)/2;
						String printGapAdjustC = printGapAdjust.substring(0,Math.min(lengthDealCB, printGapAdjust.length()));
						
						int lengthDealD = DealMobStr.length();
						int lengthDealDB =  (48 - lengthDealD)/2;
						String printGapAdjustD = printGapAdjust.substring(0,Math.min(lengthDealDB, printGapAdjust.length()));
						
						
						
						String subTitleheadA = printGapAdjustA + DealNameStr;
						String subTitleheadB = printGapAdjustB + DealAddStra;	
						String subTitleheadC = printGapAdjustC + DealAddStrb + ", " +DealAddStrc + ".";	
						String subTitleheadD = printGapAdjustD + DealMobStr;	
						String subTitleheadE = printLineSeperator;	
						
						
						String SalesRepNamestr = "Sales Rep :" + usernameStr.trim();
						int lengthDealE = SalesRepNamestr.length();
						int lengthDealEB =  (48 - lengthDealE)/2;
						String printGapAdjustE = printGapAdjust.substring(0,Math.min(lengthDealEB, printGapAdjust.length()));
						String subTitleheadF = printGapAdjustE +SalesRepNamestr;
						
						
						String SalesRepPhonestr = "Sales Phone :" + repPhone.trim();
						int lengthDealF = SalesRepPhonestr.length();
						int lengthDealFB =  (48 - lengthDealF)/2;
						String printGapAdjustF = printGapAdjust.substring(0,Math.min(lengthDealFB, printGapAdjust.length()));
						String subTitleheadG = printGapAdjustF +SalesRepPhonestr;
						
						String subTitleheadH = printLineSeperator;
						
						//***Print Customer Details***
						int lengthDealI = StrPrintDebName.length();
						int lengthDealIB =  (48 - lengthDealI)/2;
						String printGapAdjustI = printGapAdjust.substring(0,Math.min(lengthDealIB, printGapAdjust.length()));
						
						String customerAddressStr = StrPrintDebAddressA + "," +StrPrintDebAddressB;
						int lengthDealJ = customerAddressStr.length();
						int lengthDealJB =  (48 - lengthDealJ)/2;
						String printGapAdjustJ = printGapAdjust.substring(0,Math.min(lengthDealJB, printGapAdjust.length()));
						
						int lengthDealK = StrPrintDebAddressC.length();
						int lengthDealKB =  (48 - lengthDealK)/2;
						String printGapAdjustK = printGapAdjust.substring(0,Math.min(lengthDealKB, printGapAdjust.length()));
						
						int lengthDealL = StrPrintDebPhone.length();
						int lengthDealLB =  (48 - lengthDealL)/2;
						String printGapAdjustL = printGapAdjust.substring(0,Math.min(lengthDealLB, printGapAdjust.length()));
						
						// Print Customer Information
						String subTitleheadI = printGapAdjustI + StrPrintDebName;
						String subTitleheadJ = printGapAdjustJ + StrPrintDebAddressA + "," +StrPrintDebAddressB;
						String subTitleheadK = printGapAdjustK + StrPrintDebAddressC;
						String subTitleheadL = printGapAdjustL + StrPrintDebPhone;
						
						String subTitleheadO = printLineSeperator;
						
						//***Print Invoice Header***
						String subTitleheadM = "Invoice Date :"+ StrPrintDate;
						int lengthDealM = subTitleheadM.length();
						int lengthDealMB =  (48 - lengthDealM)/2;
						String printGapAdjustM = printGapAdjust.substring(0,Math.min(lengthDealMB, printGapAdjust.length()));
						
						String subTitleheadN = "Invoice Number :"+ StrPrintRefNo;
						int lengthDealN = subTitleheadN.length();
						int lengthDealNB =  (48 - lengthDealN)/2;
						String printGapAdjustN = printGapAdjust.substring(0,Math.min(lengthDealNB, printGapAdjust.length()));
						
						String subTitleheadNO = "Sales Order Number :"+ SalesOrdNo;
						int lengthDealNO = subTitleheadNO.length();
						int lengthDealNOB =  (48 - lengthDealNO)/2;
						String printGapAdjustNO = printGapAdjust.substring(0,Math.min(lengthDealNOB, printGapAdjust.length()));
						
						String subTitleheadR = "Remarks :"+ Remarks;
						int lengthDealR = subTitleheadR.length();
						int lengthDealRB =  (48 - lengthDealR)/2;
						String printGapAdjustR = printGapAdjust.substring(0,Math.min(lengthDealRB, printGapAdjust.length()));
						
						//Print Invoice Heading
						subTitleheadM = printGapAdjustM + subTitleheadM;
						subTitleheadN = printGapAdjustN + subTitleheadN;
						subTitleheadNO = printGapAdjustNO + subTitleheadNO;
						subTitleheadR = printGapAdjustR + subTitleheadR;
						
						
						String title_Print_A = "\r\n" + subTitleheadA;
						String title_Print_B = "\r\n" + subTitleheadB;
						String title_Print_C = "\r\n" + subTitleheadC;
						String title_Print_D = "\r\n" + subTitleheadD;
						String title_Print_E = "\r\n" + subTitleheadE;
						String title_Print_F = "\r\n" + subTitleheadF;
						String title_Print_G = "\r\n" + subTitleheadG;
						String title_Print_H = "\r\n" + subTitleheadH;//Line
						//********************
						String title_Print_I = "\r\n" + subTitleheadI;
						String title_Print_J = "\r\n" + subTitleheadJ;
						String title_Print_K = "\r\n" + subTitleheadK;
						String title_Print_L = "\r\n" + subTitleheadL;
						String title_Print_O = "\r\n" + subTitleheadO;
						//********************
						String title_Print_M = "\r\n" + subTitleheadM;//Line
						String title_Print_N = "\r\n" + subTitleheadN;
						
						if(SalesOrdNo.length()>=0){
							title_Print_NO = "\r\n" + subTitleheadNO;
						}
						else{
							title_Print_NO = "";
						}
						String title_Print_R = "\r\n" + subTitleheadR;
						
						//********************
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              
						if (logPrint == 1) {
							Heading_bmh = "\r" + title_Print_A + title_Print_B + title_Print_C + title_Print_D + title_Print_E + title_Print_F + title_Print_G + title_Print_H + title_Print_I + title_Print_J + title_Print_K + title_Print_L + title_Print_O +title_Print_M + title_Print_N + title_Print_NO + title_Print_R;
						}
						
						String title_cb = "\r\nProduct Name                          (CS | PS)";
						String title_cc = "\r\nDisc             Units    UnitPrice        (RS)";

						if (logPrint == 1) {
							Heading_b = "\r\n" + printLineSeperator + title_cb + title_cc + "\r\n" +printLineSeperator;
						}

						// **********Printing End**********

						Double StrPrintCaseQtyVal = Double
								.parseDouble(StrPrintCaseQty.replaceAll("[,]", ""));
						Double StrPrintPiecesQtyVal = Double
								.parseDouble(StrPrintPiecesQty.replaceAll("[,]", ""));
						Double StrPrintDiscountVal = Double
								.parseDouble(StrPrintDiscount.replaceAll("[,]", ""));
						PrintDiscountVal = PrintDiscountVal
								+ StrPrintDiscountVal;
						PrintCaseQtyVal = PrintCaseQtyVal + StrPrintCaseQtyVal;
						PrintPiecesQtyVal = PrintPiecesQtyVal
								+ StrPrintPiecesQtyVal;

						// TxnType
						item_result_1 = allrowitemsdes.getString(2);
						if (item_result_1.equals("SA")) {
							String rawAmountSales = allrowitemsdes.getString(3);
							Double rawAmountSalesVal = Double
									.parseDouble(rawAmountSales.replaceAll("[,]", ""));
							PrintSalesTotal = PrintSalesTotal
									+ rawAmountSalesVal;
						}
						if (item_result_1.equals("UR")
								|| item_result_1.equals("MR")) {
							String rawAmountSalesRet = allrowitemsdes
									.getString(3);
							Double rawAmountSalesRetVal = Double
									.parseDouble(rawAmountSalesRet.replaceAll("[,]", ""));
							PrintSalesRetTotal = PrintSalesRetTotal
									+ rawAmountSalesRetVal;
						}

						loopPrint = loopPrint + 1;

						// Log.v(TAG, "Loading Trans Type:"+item_result_1);
						if (currentRefNo.equals(item_result_1)) {
							printIndex = printIndex + 1;
							currentRefNo = allrowitemsdes.getString(2);
							// Log.v(TAG, "Printing Same Category");
							// item_result_1 = allrowitemsdes.getString(2);
							// printindex
							item_result_2 = allrowitemsdes.getString(10);
							// printitemname
							item_result_3 = allrowitemsdes.getString(6);
							// printcasesQty
							item_result_4 = allrowitemsdes.getString(4);
							// printpiecesQty
							item_result_5 = allrowitemsdes.getString(5);
							// printdiscount
							item_result_6 = allrowitemsdes.getString(12);
							// printrawvalue
							item_result_7 = allrowitemsdes.getString(3);

							String DisItemRawSum;
							String itemValDis = allrowitemsdes.getString(15);
							String itemDisPerVal = allrowitemsdes.getString(17);
							
							Double itemValDisAmt = Double.parseDouble(itemValDis.replaceAll("[,]", ""));
							String StritemValDisAmt = formatValues.format(itemValDisAmt);
							
							Double itemDisPerValAmt = Double.parseDouble(itemDisPerVal.replaceAll("[,]", ""));
							String StritemDisPerValAmt = formatValues.format(itemDisPerValAmt);
							
							double itemValueDisAmt = itemValDisAmt - itemDisPerValAmt;
							String StritemValueDisAmt = formatValues.format(itemValueDisAmt);
							
							String itemDisPer = allrowitemsdes.getString(16);
							
							if (itemDisPer.equals("0.00")) {
								DisItemRawSum = StritemValDisAmt + ")";
							} else if (itemValDis.equals("0.00")) {
								DisItemRawSum = StritemDisPerValAmt + "("
										+ itemDisPer + "%)";
							} else {
								DisItemRawSum = StritemValueDisAmt + "/"
										+ StritemDisPerValAmt + "(" + itemDisPer
										+ "%)";
							}
							// Calculate Total Value For Item without Discount
							double itemRawDiscount = Double
									.parseDouble(item_result_7.replaceAll(
											"[,]", ""));
							double iemRawTot = itemRawDiscount + itemValDisAmt;
							String PrintiemRawTot = formatValues
									.format(iemRawTot);

							HashMap<String, String> maptrdes = new HashMap<String, String>();
							item_result_2 = Integer.toString(printIndex);
							maptrdes.put("item_result_1", "");
							maptrdes.put("item_result_2", item_result_2);
							maptrdes.put("item_result_3", item_result_3);
							maptrdes.put("item_result_4", item_result_4);
							maptrdes.put("item_result_5", item_result_5);
							maptrdes.put("item_result_6", DisItemRawSum);
							// Print Cases Pieces - Item Price
							// Print Cases Pieces - Item Price
							totPiecesInCase = totPiecesInCase + printSpaceName;
							totPiecesInCase = totPiecesInCase.substring(0, Math.min(3,totPiecesInCase.length()));
							double StrItemUnitPriceVal = Double.parseDouble(StrItemUnitPrice.replaceAll("[,-]", ""));
							StrItemUnitPrice = formatValues.format(StrItemUnitPriceVal);
							maptrdes.put("item_result_6a", "U:"+ totPiecesInCase + printSpaceQty +StrItemUnitPrice);
							maptrdes.put("item_result_7", PrintiemRawTot);

							// fill in the grid_item layout
							fillMapstrdes.add(maptrdes);
							SimpleAdapter adaptertrdes = new SimpleAdapter(
									this, fillMapstrdes,
									R.layout.dm_transaction_doc_invoice_raw,
									fromtrdes, totrdes);
							lvtypedes.setAdapter(adaptertrdes);

							// Recreating Printing Format of the data
					
							String itemIndex = item_result_2 + printSpaceName;
							String PrintStritemIndex = indexcountinv.substring(
									0, Math.min(4, indexcountinv.length()));
							String itemCases = item_result_4 + printSpaceName;
							String PrintStritemCases = itemCases.substring(0,
									Math.min(3, itemCases.length()));
							String itemPieces = item_result_5 + printSpaceName;
							String PrintStritemPieces = itemPieces.substring(0,
									Math.min(3, itemPieces.length()));

							String itemDicountAmt = DisItemRawSum + printSpaceName;
							
							String PrintStritemDicountAmt = itemDicountAmt.substring(0, Math.min(15,itemDicountAmt.length()));

							String itemRawTotal = printSpaceName + item_result_7;
							PrintiemRawTot = printSpaceName + PrintiemRawTot;
							String PrintStritemRawTotal = PrintiemRawTot.substring(Math.max(PrintiemRawTot.length() - 15, 0));

							// **********Printing**********
							
							String Str_item_result_3 = item_result_3 + printSpaceName;
							String PrintItemName = Str_item_result_3.substring(0,
									Math.min(31, Str_item_result_3.length()));
							// BILL = BILL + "\r\nTrans		:"+PrintType;
							String title_d = "\r\n" + PrintStritemIndex + "."
									+ PrintItemName;
							String title_e = "(CS:"
									+ PrintStritemCases + "PS:"
									+ PrintStritemPieces+")";
							String title_f_Sub = "U:"+ totPiecesInCase + printSpaceQty +StrItemUnitPrice + printSpaceName;
							String title_f_Sub_Print = title_f_Sub.substring(0,Math.min(15, title_f_Sub.length()));
							
							String title_f = "\r\n" + "("+ PrintStritemDicountAmt +  title_f_Sub_Print + PrintStritemRawTotal;
							Log.v(TAG, "Disc xxx1 :" + PrintStritemDicountAmt);
							Heading_c = title_d + title_e + title_f;
							// **********Printing End**********

						} else {
							printIndex = printIndex + 1;
							currentRefNo = allrowitemsdes.getString(2);
							/*
							 * Log.v(TAG, "loopPrint :"+loopPrint); Log.v(TAG,
							 * "Found New Category:"+currentRefNo);
							 */
							item_result_1 = allrowitemsdes.getString(2);

							if (item_result_1.equals("SA")) {
								PrintType = "Trans : SALES";
							} else if (item_result_1.equals("UR")) {
								PrintType = "Trans : USABLE RETURN";
							} else if (item_result_1.equals("MR")) {
								PrintType = "Trans : MARKET RETURN";
							} else if (item_result_1.equals("FI")) {
								PrintType = "Trans : FREE ISSUE";
							}
							// printindex
							item_result_2 = allrowitemsdes.getString(10);
							// printitemname
							item_result_3 = allrowitemsdes.getString(6);
							// printcasesQty
							item_result_4 = allrowitemsdes.getString(4);
							// printpiecesQty
							item_result_5 = allrowitemsdes.getString(5);
							// printdiscount
							item_result_6 = allrowitemsdes.getString(9);
							// printrawvalue
							item_result_7 = allrowitemsdes.getString(3);

// Value Discount for an item
							
							String itemValDis = allrowitemsdes.getString(15);
							String itemDisPerVal = allrowitemsdes.getString(17);
							
							Double itemValDisAmt = Double.parseDouble(itemValDis.replaceAll("[,]", ""));
							String StritemValDisAmt = formatValues.format(itemValDisAmt);
							Double itemDisPerValAmt = Double.parseDouble(itemDisPerVal.replaceAll("[,]", ""));
							String StritemDisPerValAmt = formatValues.format(itemDisPerValAmt);
							double itemValueDisAmt = itemValDisAmt - itemDisPerValAmt;
							String StritemValueDisAmt = formatValues.format(itemValueDisAmt);
							
							String itemDisPer = allrowitemsdes.getString(16);

							String DisItemRawSumD;
							if (itemDisPer.equals("0.00")) {
								DisItemRawSumD = StritemValDisAmt + ")";
							} else if (itemValDis.equals("0.00")) {
								DisItemRawSumD = StritemDisPerValAmt + "("
										+ itemDisPer + "%)";
							} else {
								DisItemRawSumD = StritemValueDisAmt + "/"
										+ StritemDisPerValAmt + "(" + itemDisPer
										+ "%)";
							}
							// Calculate Total Value For Item without Discount
							double itemRawDiscount = Double
									.parseDouble(item_result_7.replaceAll(
											"[,]", ""));
							double iemRawTot = itemRawDiscount + itemValDisAmt;
							String PrintiemRawTot = formatValues
									.format(iemRawTot);

							HashMap<String, String> maptrdes = new HashMap<String, String>();
							item_result_2 = Integer.toString(printIndex);
							maptrdes.put("item_result_1", PrintType);
							maptrdes.put("item_result_2", item_result_2);
							maptrdes.put("item_result_3", item_result_3);
							maptrdes.put("item_result_4", item_result_4);
							maptrdes.put("item_result_5", item_result_5);
							maptrdes.put("item_result_6", DisItemRawSumD);
							// Print Cases Pieces - Item Price
							// Print Cases Pieces - Item Price
							totPiecesInCase = totPiecesInCase + printSpaceName;
							totPiecesInCase = totPiecesInCase.substring(0, Math.min(3,totPiecesInCase.length()));
							double StrItemUnitPriceVal = Double.parseDouble(StrItemUnitPrice.replaceAll("[,-]", ""));
							StrItemUnitPrice = formatValues.format(StrItemUnitPriceVal);
							maptrdes.put("item_result_6a", "U:"+ totPiecesInCase + printSpaceQty +StrItemUnitPrice);
							maptrdes.put("item_result_7", PrintiemRawTot);


							// fill in the grid_item layout
							fillMapstrdes.add(maptrdes);
							SimpleAdapter adaptertrdes = new SimpleAdapter(
									this, fillMapstrdes,
									R.layout.dm_transaction_doc_invoice_raw,
									fromtrdes, totrdes);
							lvtypedes.setAdapter(adaptertrdes);

							// Recreating Printing Format of the data
							
							String itemIndex = item_result_2 + printSpaceName;
							String PrintStritemIndex = indexcountinv.substring(
									0, Math.min(4, indexcountinv.length()));
							String itemCases = item_result_4 + printSpaceName;
							String PrintStritemCases = itemCases.substring(0,
									Math.min(3, itemCases.length()));
							String itemPieces = item_result_5 + printSpaceName;
							String PrintStritemPieces = itemPieces.substring(0,
									Math.min(3, itemPieces.length()));
							String itemDicountAmt = DisItemRawSumD
									+ printSpaceName;
							
							
							String PrintStritemDicountAmt = itemDicountAmt.substring(0, Math.min(15,itemDicountAmt.length()));

							String itemRawTotal = printSpaceName
									+ item_result_7;
							PrintiemRawTot = printSpaceName + PrintiemRawTot;
							String PrintStritemRawTotal = PrintiemRawTot.substring(Math.max(PrintiemRawTot.length() - 15, 0));

							// **********Printing**********
							String Str_item_result_3 = item_result_3 + printSpaceName;
							String PrintItemName = Str_item_result_3.substring(0,
									Math.min(31, Str_item_result_3.length()));
							
							String title_g = "\r\n" + PrintType;
							String title_h = "\r\n" + PrintStritemIndex + "."
									+ PrintItemName;
							String title_i = "(CS:"
									+ PrintStritemCases + "PS:"
									+ PrintStritemPieces+")";
							String title_j = "\r\n" + PrintStritemDicountAmt + printSpaceQty + PrintStritemRawTotal;
							
							String title_f_Sub = "U:"+ totPiecesInCase + printSpaceQty +StrItemUnitPrice + printSpaceName;
							String title_f_Sub_Print = title_f_Sub.substring(0,Math.min(15, title_f_Sub.length()));
							
							String title_f = "\r\n" + "("+ PrintStritemDicountAmt +  title_f_Sub_Print + PrintStritemRawTotal;
					
							Log.v(TAG, "Disc xxx2 :" + PrintStritemDicountAmt);
							Heading_d = title_g + title_h + title_i + title_f;

							// **********Printing End**********
						}

						Cursor getprintString = null;
						try {
							String queryPStr = "SELECT * from FInvLogPrint";
							getprintString = mydb.rawQuery(queryPStr, null);
							if (getprintString.getCount() > 0) {
								while (getprintString.moveToNext()) {
									currentIndex = getprintString.getString(0);
									CurrentStringPrint = getprintString
											.getString(1);

									String updatingArray = "\r\n"
											+ CurrentStringPrint + Heading_a
											+ Heading_bmh + Heading_b
											+ Heading_d + Heading_c;

									ContentValues savePrintArrayUpdate = new ContentValues();
									savePrintArrayUpdate.put("printArray",
											updatingArray);
									mydb.update(LOGPRINTSTRING,
											savePrintArrayUpdate, "print_id ='"
													+ currentIndex + "'", null);
									Heading_a = "";
									Heading_b = "";
									Heading_c = "";
									Heading_d = "";
									Heading_bmh = "";
								}
							} else {
								ContentValues savePrintArray = new ContentValues();
								String saveArray = Heading_a + Heading_bmh
										+ Heading_b + Heading_c + Heading_d;
								savePrintArray.put("printArray", saveArray);
								mydb.insert(LOGPRINTSTRING, null,
										savePrintArray);
								Heading_a = "";
								Heading_b = "";
								Heading_bmh = "";
								Heading_c = "";
								Heading_d = "";
							}
						} catch (Exception e) {
						}
						getprintString.close();
					}
				}
			} else {
				Log.v(TAG, "***************************");
			}

			printrefno.setText("Invoice Number :" + StrPrintRefNo);
			if(SalesOrdNo.length() >=0){
				txtprintsordrefno.setVisibility(View.VISIBLE);
				txtprintsordrefno.setText(SalesOrdNo);
			}
			printdate.setText ("Invoice Date   :" + StrPrintDate);
			printremark.setText("Remarks : " + Remarks);
			printcus.setText(StrPrintDebName);
			printcusaddress.setText(StrPrintDebAddressA + "," +StrPrintDebAddressB);
			printcusaddressb.setText(StrPrintDebAddressC);
			printcusphoneno.setText(StrPrintDebPhone);
			//txtprintsordrefno.setText(SalesOrdNo);
			//printremark.setText(Remarks);
			//Print Total cases and pieces Summary
			
			
			try{
		    	Integer PrintCaseQtyValInt = PrintCaseQtyVal.intValue(); 
		    	//String printCaseQuantity = Double.toString(PrintCaseQtyVal);
		    	printCaseQuantity = Integer.toString(PrintCaseQtyValInt);
				printtotcaseqty.setText(printCaseQuantity);
				
				Integer PrintPiecesQtyValInt = PrintPiecesQtyVal.intValue(); 
				//String printPicesQuantity = Double.toString(PrintPiecesQtyVal);
				printPicesQuantity = Integer.toString(PrintPiecesQtyValInt);
				printtotpiecesqty.setText(printPicesQuantity);
		    }
		    catch(Exception e){
		    	String printCaseQuantity = Double.toString(PrintCaseQtyVal);
				printtotcaseqty.setText(printCaseQuantity);
				printPicesQuantity = Double.toString(PrintPiecesQtyVal);
				printtotpiecesqty.setText(printPicesQuantity);
		    }
			
			
			
			
			//Print Market return total value
			String PrintSalesRetTotalStr = formatValues.format(PrintSalesRetTotal);// Double.toString(PrintSalesRetTotal);
			printmktrettot.setText(PrintSalesRetTotalStr);
			
			//Print Invoice Total Amount After Discount
			Double NetTotalValuePrintVal = Double.parseDouble(NetTotalValuePrint.replaceAll("[,]", ""));
			String PrintNetTotalValuePrintVal = formatValues.format(NetTotalValuePrintVal);
			printnettotal.setText(PrintNetTotalValuePrintVal);
			
			
			//Print Line Items Discount Value Total
			String PrintDiscountValStr = formatValues.format(PrintDiscountVal); // Double.toString(PrintDiscountVal);
			printtotdis.setText(PrintDiscountValStr);
			
			//Total Discount Value 
			Double TotalStrPrintDiscountVal = Double.parseDouble(TotalStrPrintDiscount.replaceAll("[,]", ""));
			Log.v(TAG, "TotalStrPrintDiscount:" + TotalStrPrintDiscount);
			//Take Cutomer Discount Ratio Value(Part of Invoice Discount)
			Double CustomerDiscountValue = TotalStrPrintDiscountVal - PrintDiscountVal;
			Log.v(TAG, "CustomerDiscountValue:" + CustomerDiscountValue);
			//Customer manual discount value 
			Double TotalInvoiceDiscountValCus = Double.parseDouble(TotalInvoiceDiscount.replaceAll("[,]", ""));
			//Print Invoice Discount Value Total
			Double totalInvoiceDicount = CustomerDiscountValue;
			/*Double totalInvoiceDicount = CustomerDiscountValue + TotalInvoiceDiscountValCus;*/
			totalInvoiceDicountStr = formatValues.format(totalInvoiceDicount); 
			printtotinvdis.setText(totalInvoiceDicountStr);
			
			//Print Gross Sales Total Value
			Double totalGrossSalesValue = PrintDiscountVal + totalInvoiceDicount + NetTotalValuePrintVal - PrintSalesRetTotal;
			Log.v(TAG, "totalGrossSalesValue:" + CustomerDiscountValue);
			
			Double StrDisPerRatioVal = Double.parseDouble(StrDisPerRatio.replaceAll("[,]", ""));
			if(StrDisPerRatioVal <= 0.0){
				printMainInvDiscount = "Header Discount";
				invoicediscountSummary.setText("Header Discount");
				
				totalGrossSalesValueStr = formatValues.format(totalGrossSalesValue); 
				printgrosssalestot.setText(totalGrossSalesValueStr);
			}
			else{
				Double DisRatioVal = TotalStrPrintDiscountVal - PrintDiscountVal - TotalInvoiceDiscountValCus;
				//printMainInvDiscount = "Header Discount:"+formatValues.format(DisRatioVal)+"("+StrDisPerRatio+"%)";
				invoicediscountSummary.setText("Header Discount: " + "("+StrDisPerRatio+"%)");
				printMainInvDiscount = "Header Discount: " + "("+StrDisPerRatio+"%)";
				//invoicediscountSummary.setText("Header Discount");
				
				totalGrossSalesValueStr = formatValues.format(totalGrossSalesValue); 
				printgrosssalestot.setText(totalGrossSalesValueStr);
			}

			
			//**************Print Summary***************************

			String printSpaceSumName = "                    ";

			String summaryTitle_a = "Total Quantity" + printSpaceSumName;
			summaryTitle_a = summaryTitle_a.substring(0,
					Math.min(20, summaryTitle_a.length()));

			// -----------------------------------------------------------------
			String summaryTitle_b = "Total Market Return" + printSpaceSumName;
			summaryTitle_b = summaryTitle_b.substring(0,
					Math.min(27, summaryTitle_b.length()));
			String summaryTitle_b_Val = printSpaceSumName
					+ PrintSalesRetTotalStr;
			summaryTitle_b_Val = summaryTitle_b_Val.substring(Math.max(
					summaryTitle_b_Val.length() - 18, 0));
			// -----------------------------------------------------------------
			String summaryTitle_c = "Total Value" + printSpaceSumName;
			summaryTitle_c = summaryTitle_c.substring(0,
					Math.min(27, summaryTitle_c.length()));
			String summaryTitle_c_Val = printSpaceSumName
					+ totalGrossSalesValueStr;
			summaryTitle_c_Val = summaryTitle_c_Val.substring(Math.max(
					summaryTitle_c_Val.length() - 18, 0));
			// -----------------------------------------------------------------
			String summaryTitle_d = "Line Discount " + printSpaceSumName;
			summaryTitle_d = summaryTitle_d.substring(0,
					Math.min(27, summaryTitle_d.length()));
			String summaryTitle_d_Val = printSpaceSumName + PrintDiscountValStr;
			summaryTitle_d_Val = summaryTitle_d_Val.substring(Math.max(
					summaryTitle_d_Val.length() - 18, 0));

			// -----------------------------------------------------------------
			String summaryTitle_dd = printMainInvDiscount + printSpaceSumName;
			summaryTitle_dd = summaryTitle_dd.substring(0,
					Math.min(27, summaryTitle_dd.length()));
			String summaryTitle_dd_Val = printSpaceSumName + totalInvoiceDicountStr;
			summaryTitle_dd_Val = summaryTitle_dd_Val.substring(Math.max(
					summaryTitle_dd_Val.length() - 18, 0));
			// -----------------------------------------------------------------
			String summaryTitle_e = "Net Total" + printSpaceSumName;
			summaryTitle_e = summaryTitle_e.substring(0,
					Math.min(27, summaryTitle_e.length()));
			String summaryTitle_e_Val = printSpaceSumName + PrintNetTotalValuePrintVal;
			summaryTitle_e_Val = summaryTitle_e_Val.substring(Math.max(
					summaryTitle_e_Val.length() - 18, 0));

			String buttomTitlea = "\r\n\n" + summaryTitle_a + "Cases  : " + printCaseQuantity;
			String buttomTitleab = "\r\n"  + printSpaceSumName + "Pieces : " + printPicesQuantity;
			
			String buttomTitleb = "\r\n" + summaryTitle_b + summaryTitle_b_Val;
			String buttomTitlec = "\r\n" + summaryTitle_c + summaryTitle_c_Val;
			String buttomTitled = "\r\n" + summaryTitle_d + summaryTitle_d_Val;
			String buttomTitledd = "\r\n" + summaryTitle_dd + summaryTitle_dd_Val;
			String buttomTitlee = "\r\n" + summaryTitle_e + summaryTitle_e_Val;
			String buttomTitlef = "\r\n\n\n" +"Good Received................................";
			String buttomTitlefa = "\r\n\n\n" + "Please place The Rubber Stamp";

			String buttomRaw =  "\r\n" + printLineSeperator + buttomTitlea + buttomTitleab + buttomTitlec 
					+ buttomTitleb + buttomTitledd + buttomTitled + buttomTitlee +"\r\n" + printLineSeperator+ buttomTitlef + buttomTitlefa +"\r\n\n\n\n\n\n\n" + printLineSeperator+"\n";
			Cursor getprintSummary = null;
			try {
				String queryPStr = "SELECT * from FInvLogPrint";
				getprintSummary = mydb.rawQuery(queryPStr, null);
				if (getprintSummary.getCount() > 0) {
					while (getprintSummary.moveToNext()) {
						currentIndex = getprintSummary.getString(0);
						CurrentStringPrint = getprintSummary.getString(1);

						String updatingArray = "\r\n"
								+ CurrentStringPrint
								+ buttomRaw;

						ContentValues savePrintArrayUpdate = new ContentValues();
						savePrintArrayUpdate.put("printArray", updatingArray);
						mydb.update(LOGPRINTSTRING, savePrintArrayUpdate,
								"print_id ='" + currentIndex + "'", null);
					}
				}

			} catch (Exception e) {
			}

			callPrintDevice();
			allrowitemsdes.close();
			mydb.close();
		} catch (Exception e) {
		}

		// PrintDiscountVal,PrintSalesTotal,PrintSalesRetTotal
		// printmktrettot,printgrosssalestot,printtotdis,printnettotal
		DM_List_Expand_Helper.getListViewSize(lvtypedes);
	}

	private void callPrintDevice() {
		BILL = " ";
		// TODO Auto-generated method stub
		// PRINTER_MAC_ID = "AC:3F:A4:12:D7:E8";
		// PRINTER_MAC_ID = "00:22:58:3A:C6:49";
		Cursor getprintString = null;
		try {
			String queryPStr = "SELECT * from FInvLogPrint";
			getprintString = mydb.rawQuery(queryPStr, null);
			if (getprintString.getCount() > 0) {
				while (getprintString.moveToNext()) {
					CurrentStringPrint = getprintString.getString(1);
					BILL = CurrentStringPrint;
					Log.v(TAG, "BILL :" + BILL);
					mBTAdapter = BluetoothAdapter.getDefaultAdapter();
					dialogProgress = new Dialog(
							DM_Print_Main_Invoice_Active.this);

					try {
						if (mBTAdapter.isDiscovering())
							mBTAdapter.cancelDiscovery();
						else
							mBTAdapter.startDiscovery();
					} catch (Exception e) {
						Log.e("Class ", "My Exe ", e);
					}
					System.out.println("BT Searching status :"
							+ mBTAdapter.isDiscovering());
					if (mBTAdapter == null) {
						Toast.makeText(this,
								"Device has no bluetooth capability",
								Toast.LENGTH_LONG).show();
						finish();
					} else {
						if (!mBTAdapter.isEnabled()) {
							Intent i = new Intent(
									BluetoothAdapter.ACTION_REQUEST_ENABLE);
							startActivityForResult(i, 0);
						}

						// Register the BroadcastReceiver
						IntentFilter filter = new IntentFilter(
								BluetoothDevice.ACTION_FOUND);
						registerReceiver(mReceiver, filter); // Don't forget to
																// unregister
																// during
																// onDestroy
						dialogProgress.setTitle("Finding printer...");
						dialogProgress
								.setOnDismissListener(new DialogInterface.OnDismissListener() {
									public void onDismiss(DialogInterface dialog) {
										dialog.dismiss();
										setResult(RESULT_CANCELED);
										finish();
									}
								});
						dialogProgress.show();

					}
				}
			}
		} catch (Exception e) {
		}

	}

	public void printBillToDevice(final String address) {
		new Thread(new Runnable() {

			public void run() {
				runOnUiThread(new Runnable() {

					public void run() {
						dialogProgress.setTitle("Connecting...");
						dialogProgress.show();
					}

				});

				mBTAdapter.cancelDiscovery();

				try {
					System.out
							.println("**************************#****connecting");
					BluetoothDevice mdevice = mBTAdapter
							.getRemoteDevice(address);
					Method m = mdevice.getClass().getMethod(
							"createRfcommSocket", new Class[] { int.class });
					mBTSocket = (BluetoothSocket) m.invoke(mdevice, 1);

					mBTSocket.connect();
					OutputStream os = mBTSocket.getOutputStream();
					os.flush();

					os.write(BILL.getBytes());
					System.out.println(BILL);

					if (mBTAdapter != null)
						mBTAdapter.cancelDiscovery();
					setResult(RESULT_OK);
					finish();
				} catch (Exception e) {
					Log.e("Class ", "My Exe ", e);
					// Toast.makeText(BluetoothPrint.this, ERROR_MESSAGE,
					// Toast.LENGTH_SHORT).show();
					e.printStackTrace();
					setResult(RESULT_CANCELED);
					finish();

				}

				runOnUiThread(new Runnable() {

					public void run() {
						try {
							dialogProgress.dismiss();
						} catch (Exception e) {
							Log.e("Class ", "My Exe ", e);
						}
					}

				});

			}

		}).start();
	}

	@Override
	protected void onDestroy() {
		Log.i("Dest ", "Checking Ddest");
		super.onDestroy();
		try {
			if (dialogProgress != null)
				dialogProgress.dismiss();
			if (mBTAdapter != null)
				mBTAdapter.cancelDiscovery();
			this.unregisterReceiver(mReceiver);
		} catch (Exception e) {
			Log.e("Class ", "My Exe ", e);
		}
	}

	private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
		public void onReceive(Context context, Intent intent) {

			try {
				String action = intent.getAction();
				// When discovery finds a device
				if (BluetoothDevice.ACTION_FOUND.equals(action)) {
					// Get the BluetoothDevice object from the Intent
					BluetoothDevice device = intent
							.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
					System.out.println("***" + device.getName() + " : "
							+ device.getAddress());

					if (device.getAddress().equalsIgnoreCase(PRINTER_MAC_ID)) {
						mBTAdapter.cancelDiscovery();
						dialogProgress.dismiss();
						/*
						 * Toast.makeText(DM_Print_Main_Invoice_Active.this,
						 * device.getName() + " Printing data",
						 * Toast.LENGTH_LONG).show();
						 */
						printBillToDevice(PRINTER_MAC_ID);
						/*
						 * Toast.makeText(DM_Print_Main_Invoice_Active.this,
						 * device.getName() + " found", Toast.LENGTH_LONG)
						 * .show();
						 */
					}
				}
			} catch (Exception e) {
				Log.e("Class  ", "My Exe ", e);
				// Toast.makeText(BluetoothPrint.this, ERROR_MESSAGE,
				// Toast.LENGTH_SHORT).show();

			}
		}
	};

	@Override
	public void onBackPressed() {
		try {
			if (mBTAdapter != null)
				mBTAdapter.cancelDiscovery();
			this.unregisterReceiver(mReceiver);
		} catch (Exception e) {
			Log.e("Class ", "My Exe ", e);
		}
		setResult(RESULT_CANCELED);
		finish();
	}
}
